<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Mall\Goods;
use App\Models\Mall\GoodsType;
use App\Models\Mall\GoodsTypeRelate;
use App\Models\Mall\Order;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class MallController extends Controller
{
	public function goods(Request $request)
	{
		$goods = Goods::orderBy('id', 'desc')->paginate(10);

		$data['list'] = $goods;
		$data['params'] = $request->all();

		return view('admin.mall.goodslist', $data);
	}

	public function order(Request $request)
	{
		$orders = Order::where('status', 1)->orderBy('id', 'desc')->paginate(10);

		$data['list'] = $orders;
		$data['params'] = $request->all();

		return view('admin.mall.order', $data);
	}

	public function edit(Request $request)
	{
		$id 	  = $request->input('id');

        $data['goods'] 	  = Goods::find( $id );
        $data['types'] 	  = GoodsType::get();

        return view('admin.mall.add', $data);        
	}

	public function save(Request $request)
	{
		$id 	  = $request->input('id');

		$goods  = Goods::find( $id ) ?: new Goods;

		if ( $request->hasFile('file') ) {
			$file          = $request->file('file');
			$path          = '/upfiles/mall/goods/' . date('YmdHis') . '.png';
			Image::make($file)->save(public_path($path));
			$goods->images = $path;	
		}
		//加商品缩略图
		if ( $request->hasFile('thumbnail') ) {
			$file          = $request->file('thumbnail');
			$path          = '/upfiles/mall/goods/' . date('YmdHis') . '_a.png';
			Image::make($file)->save(public_path($path));
			$goods->thumbnail = $path;
		}

        $fields   = ['name', 'tag', 'price', 'original_price', 'need_xyb', 'need_jb', 'description', 'taobao_url'];
        foreach ($fields as $field) {
            if ($request->has($field)) {
                $goods->$field = $request->input($field);
            }
        }

        $ret = $goods->save();

        $goods->types()->detach();
        $goods->types()->attach( $request->input('types') );

        if ( $ret ) {
            echo "<meta http-equiv=\"refresh\" content=\"2; url='http://ga.cloudxt.cn/admin_1427a/mall/goods'\">保存成功";
        } else {
            echo "保存失败";
        }
	}
}